package com.jack.blog.utils;

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * parse md to html
 */
public final class MdUtil {
    private static final String before="<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>Title</title></head><body>";
    private static final String after="</body></html>";

    public static void mdToHtml(InputStream md, OutputStream html)throws Exception{
        if (md==null||html==null)throw new IllegalArgumentException("null inputStream!");
        StringBuilder builder=new StringBuilder();
        builder.append(before);
        Parser parser = Parser.builder().build();
        Node node = parser.parseReader(new InputStreamReader(md));
        HtmlRenderer render = HtmlRenderer.builder().build();
        builder.append(render.render(node));
        builder.append(after);
        html.write(builder.toString().getBytes(StandardCharsets.UTF_8));
        md.close();
        html.close();
    }

}
